package messagesvc.biz.impl;

import cn.hutool.core.util.StrUtil;
import cn.ucloud.microsf.messagesvc.biz.MessageFormatter;
import java.util.Map;

public class DefaultMessageFormatter implements MessageFormatter {

  private final static StringBuilder P_L = new StringBuilder("$").append("{");
  private final static String P_R = "}";

  @Override
  public String format(String content, Map<String, String> params) {

    if (StrUtil.isBlank(content)) {
      return content;
    }

    if (!StrUtil.contains(content, P_L)) {
      return content;
    }

    String[] strings = StrUtil.split(content, P_L);

    StringBuilder builder = new StringBuilder();

    for (String string : strings) {
      int rIndex = string.indexOf(P_R);
      if (rIndex > 0) {
        String key = string.substring(0, rIndex);
        String value = params.get(key);
        builder.append(string.replace(key + P_R, StrUtil.trimToEmpty(value)));
      } else {
        builder.append(string);
      }
    }
    return builder.toString();
  }
}
